package com.banban.user.task;

import com.alibaba.fastjson.JSON;
import com.banban.user.config.TaskProperties;
import com.banban.user.domain.*;
import com.banban.user.mapper.*;
import com.banban.user.service.ConversationSummarizeService;
import com.banban.user.service.PromptTemplateService;
import com.banban.user.service.UserService;
import com.banban.user.util.DeepSeekSendMessage;
import com.banban.user.util.PushUtil;
import com.banban.user.util.RedisUtil;
import com.banban.user.util.UniqueIDUtil;
import com.banban.user.vo.ConversationLogVO;
import com.banban.user.vo.PromptTemplateVO;
import com.banban.user.vo.UserProfileDetailVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDate;
import java.util.*;

@Component
public class UserProfileTask {

    @Autowired
    private TaskProperties taskProperties;

    @Resource
    private ConversationLogMapper conversationLogMapper;

    @Autowired
    private DeepSeekSendMessage deepSeekSendMessage;

    @Resource
    private PromptTemplateService promptTemplateService;

    @Value("${promptTemplateId}")
    private String promptTemplateId;

    @Autowired
    private ConversationSummarizeService conversationSummarizeService;

    @Resource
    private UserProfileMapper userProfileMapper;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private UserLoginRecordMapper loginRecordMapper;

    @Resource
    private SessionInfoMapper sessionInfoMapper;

    @Resource
    private UserCidMapper cidMapper;

    @Autowired
    private PushUtil pushUtil;

    @Resource
    private UserService userService;
    private static final String BANBAN_USER_MESSAGE = "BANBAN_USER_MESSAGE_";

    @Scheduled(cron = "${task.cron}") // 每天1点秒执行一次
    public void extUserProfile() {
//        System.out.println("Fixed Rate Task executed at: " + System.currentTimeMillis());
        List<String> createBys = conversationLogMapper.selectCreateBy(taskProperties.getDay());
        if (createBys.isEmpty()) {
            return;
        }
        PromptTemplateVO promptById = promptTemplateService.getPromptById(promptTemplateId);
        String promptTemplate = promptById.getPrompt();
        for (String createBy : createBys) {
            List<ConversationLog> list = conversationLogMapper.selectByUserId(createBy, taskProperties.getDay());
            List<ConversationLogVO> vos = new ArrayList<>();
            if (!list.isEmpty()) {
                for (ConversationLog conversationLog : list) {
                    ConversationLogVO vo = new ConversationLogVO();
                    BeanUtils.copyProperties(conversationLog, vo);
                    vos.add(vo);
                }
                String prompt = vos.toString();
                //调用大模型
                String response;
                try {
                    response = deepSeekSendMessage.getResponse(prompt, promptTemplate);
                } catch (IOException e) {
                    continue;
                }
                if (StringUtils.isNotEmpty(response)) {
                    List<UserProfileDetailVO> userProfileDetailVOS = JSON.parseArray(response, UserProfileDetailVO.class);
                    for (UserProfileDetailVO userProfileDetailVO : userProfileDetailVOS) {
                        UserProfile userProfile = new UserProfile();
                        BeanUtils.copyProperties(userProfileDetailVO, userProfile);
                        userProfile.setUserId(createBy);
                        //查询是否之前有，如果有，则更新，没有则新增
                        List<UserProfile> result = userProfileMapper.select(userProfile);
//                        UserProfile selectOne = userProfileMapper.select(userProfile);
                        if (result != null && !result.isEmpty() && !userProfileDetailVO.getField().equals("personalizedDemand")){
                            UserProfile selectOne = result.get(0);
                            userProfile.setValue(selectOne.getValue() + "," + userProfile.getValue());
                            userProfileMapper.updateByUserIdAndField(userProfile);
                        }else {
                            userProfile.setId(String.valueOf(UniqueIDUtil.generateId()));
                            userProfileMapper.insert(userProfile);
                        }
//                        if (selectOne != null) {
//                            userProfile.setValue(selectOne.getValue() + "," + userProfile.getValue());
//                            userProfileMapper.updateByUserIdAndField(userProfile);
//                        } else {
//                            userProfile.setId(String.valueOf(UniqueIDUtil.generateId()));
//                            userProfileMapper.insert(userProfile);
//                        }
                    }
                }
            }
        }
    }


    /**
     * 每天定时删除重复数据
     */
    @Scheduled(cron = "0 0 4 * * ?") // 每天凌晨4点执行
    public void cleanDuplicateUserProfiles() {
        // 查询所有重复的记录
        List<Map<String, Object>> duplicates = userProfileMapper.selectByCondition();

        // 遍历重复记录，删除旧的记录
        for (Map<String, Object> duplicate : duplicates) {
            String userId = (String) duplicate.get("user_id");
            String field = (String) duplicate.get("field");
            String value = (String) duplicate.get("value");
            Date maxUpdateTime = (Date) duplicate.get("max_update_time");

            QueryWrapper<UserProfile> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId)
                    .eq("field", field)
                    .eq("value", value)
                    .lt("update_time", maxUpdateTime).ne("field", "personalizedDemand");

            int deleted = userProfileMapper.delete(queryWrapper);
            System.out.println("Deleted " + deleted + " duplicate rows for user_id: " + userId + ", field: " + field + ", value: " + value);
        }
    }


    /**
     * 每天定时总计用户当天交互内容
     */
    @Scheduled(cron = "0 0 2 * * ?") // 每天凌晨2点执行
    public void conversationSummarize() {
        List<String> createBys = conversationLogMapper.selectCreateByYesterday();
        if (createBys.isEmpty()) {
            return;
        }

        String promptTemplate = "你是一位优秀的会话总结分析人员，请根据用户输入的对话信息，精准归纳为一句话，尽量包含对话内容的全部重要信息，内容不要太长，50字以内即可";
        for (String createBy : createBys) {
            List<ConversationLog> list = conversationLogMapper.selectByUserIdYesterday(createBy);
            List<ConversationLogVO> vos = new ArrayList<>();
            if (!list.isEmpty()) {
                for (ConversationLog conversationLog : list) {
                    ConversationLogVO vo = new ConversationLogVO();
                    BeanUtils.copyProperties(conversationLog, vo);
                    vos.add(vo);
                }
                String prompt = vos.toString();
                //调用大模型
                String response;
                try {
                    response = deepSeekSendMessage.getResponse(prompt, promptTemplate);
                } catch (IOException e) {
                    continue;
                }
                ConversationSummarize summer = new ConversationSummarize();
                summer.setUserId(createBy);
                summer.setContent(response);
                summer.setDateTime(LocalDate.now().minusDays(1));
                conversationSummarizeService.save(summer);
            }
        }
    }


    /**
     * 每天定时设置用户画像
     */
    @Scheduled(cron = "0 0 4 * * ?") // 每天凌晨4点执行
    public void setUserProfileToRedis() {
        List<SysUser> list = userService.list();
        if (list != null && !list.isEmpty()) {
            for (SysUser sysUser : list) {
                String userId = sysUser.getId();
                List<UserProfile> userProfiles = userProfileMapper.selectByUserId(userId);
                if (userProfiles != null && !userProfiles.isEmpty()){
                    Map<String, String> map = new HashMap<>();
                    for (UserProfile userProfile : userProfiles) {
                        map.put(userProfile.getField(), userProfile.getValue());
                    }
                    redisUtil.set(BANBAN_USER_MESSAGE + userId, map);
                }
            }
        }
    }

    /**
     * 每天晚上8点推送消息
     */
    @Scheduled(cron = "0 0 20 * * ?") // 每天晚上8点执行
    public void push() {
        //一天未的用户
        List<String> userIds = loginRecordMapper.selectUserIdByTime(1);
        if (!userIds.isEmpty()){
            for (String userId : userIds) {
                SysUser user = userService.getById(userId);
                if (user==null){
                    continue;
                }
                List<String> cids = cidMapper.selectCidByUserId(userId);
                if (cids.isEmpty()){
                    continue;
                }
                String nickName = user.getNickName();
                LambdaQueryWrapper<SessionInfo> lqwSession = new LambdaQueryWrapper<>();
                lqwSession.eq(SessionInfo::getUserId, userId);
                lqwSession.orderByDesc(SessionInfo::getCreateTime);
                lqwSession.last("limit 1");
                SessionInfo sessionInfo = sessionInfoMapper.selectOne(lqwSession);
                String sessionId = sessionInfo.getSessionId();
                LambdaQueryWrapper<ConversationLog> lqwConversationLog = new LambdaQueryWrapper<>();
                lqwConversationLog.eq(ConversationLog::getSessionId, sessionId);
                List<ConversationLog> conversationLogs = conversationLogMapper.selectList(lqwConversationLog);
                String response;
                String systemMessage = "我们开发了一款名为伴伴的陪伴类的手机应用app，为了提高用户粘性，需要针对用户昨天与大模型交互的记录生成一段提醒或者挽留类的推送消息，类似'还记得你上次说要XXXX（上次聊天核心内容），后来怎么了，我还想着这件事呢'这种话术，不超过50字，主旨在提高用户粘性，让用户乐意点击推送内容进入app，仅输出对应话术即可，其他内容不要说";
                String prompt;
                StringBuilder sb = new StringBuilder();
                for (ConversationLog conversationLog : conversationLogs) {
                    sb.append("用户：").append(conversationLog.getUserMessage()).append("\n");
                    sb.append("大模型：").append(conversationLog.getAssistantMessage()).append("\n");
                }
                prompt = sb.toString();
                try {
                    response = deepSeekSendMessage.getResponse(prompt, systemMessage);
                } catch (IOException e) {
                    continue;
                }
                String title = "Hello，" + nickName;
                for (String cid : cids) {
                    pushUtil.push(cid,title,response);
                }
            }
        }

        //3日未登录用户
        List<String> userIds3 = loginRecordMapper.selectUserIdByTime(3);
        if (!userIds.isEmpty()){
            for (String userId : userIds3) {
                SysUser user = userService.getById(userId);
                if (user==null){
                    continue;
                }
                List<String> cids = cidMapper.selectCidByUserId(userId);
                if (cids.isEmpty()){
                    continue;
                }
                LambdaQueryWrapper<SessionInfo> lqwSession = new LambdaQueryWrapper<>();
                lqwSession.eq(SessionInfo::getUserId, userId);
                lqwSession.orderByDesc(SessionInfo::getCreateTime);
                lqwSession.last("limit 1");
                SessionInfo sessionInfo = sessionInfoMapper.selectOne(lqwSession);
                if (sessionInfo == null){
                    continue;
                }
                String sessionId = sessionInfo.getSessionId();
                LambdaQueryWrapper<ConversationLog> lqwConversationLog = new LambdaQueryWrapper<>();
                lqwConversationLog.eq(ConversationLog::getSessionId, sessionId);
                List<ConversationLog> conversationLogs = conversationLogMapper.selectList(lqwConversationLog);
                String response;
                String systemMessage = "我们开发了一款名为伴伴的陪伴类的手机应用app，为了提高用户粘性，需要针对用户三天前与大模型交互的记录生成一段提醒或者挽留类的推送消息，类似'我还记得你上次说XXXX（上次聊天核心内容），后来怎么了'这种话术，不超过50字，主旨在提高用户粘性，让用户乐意点击推送内容进入app，仅输出对应话术即可，其他内容不要说";
                String prompt;
                StringBuilder sb = new StringBuilder();
                for (ConversationLog conversationLog : conversationLogs) {
                    sb.append("用户：").append(conversationLog.getUserMessage()).append("\n");
                    sb.append("大模型：").append(conversationLog.getAssistantMessage()).append("\n");
                }
                prompt = sb.toString();
                try {
                    response = deepSeekSendMessage.getResponse(prompt, systemMessage);
                } catch (IOException e) {
                    continue;
                }
                String title = "好几天没联系，不会把我忘了吧";
                for (String cid : cids) {
                    pushUtil.push(cid,title,response);
                }
            }
        }

        //7日未登录用户
        List<String> userIds7 = loginRecordMapper.selectUserIdByTime(7);
        if (!userIds.isEmpty()){
            for (String userId : userIds7) {
                SysUser user = userService.getById(userId);
                if (user==null){
                    continue;
                }
                List<String> cids = cidMapper.selectCidByUserId(userId);
                if (cids.isEmpty()){
                    continue;
                }
                String title = "hello，这周过得如何";
                String content = "讲真的，我是有点想你了呢~";
                for (String cid : cids) {
                    pushUtil.push(cid,title,content);
                }
            }
        }

        //14日未登录用户
        List<String> userIds14 = loginRecordMapper.selectUserIdByTime(14);
        if (!userIds.isEmpty()){
            for (String userId : userIds14) {
                SysUser user = userService.getById(userId);
                if (user==null){
                    continue;
                }
                List<String> cids = cidMapper.selectCidByUserId(userId);
                if (cids.isEmpty()){
                    continue;
                }
                String title = "honey，最近过得如何";
                String content = "你不会有新朋友了，把我忘记了吧~";
                for (String cid : cids) {
                    pushUtil.push(cid,title,content);
                }
            }
        }
    }

}
